<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="医代名称" prop="agentMrName">
              <el-input v-model="queryParams.agentMrName" placeholder="请输入医代名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
                <el-option v-for="dict in busi_store_refund_apply_status" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="审核员" prop="auditBy">
              <el-input v-model="queryParams.auditBy" placeholder="请输入审核员" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <el-table v-loading="loading" :data="agentMrRefundApplyList" @selection-change="handleSelectionChange">
        <el-table-column type="expand">
          <template #default="scope">
            <el-table :data="scope.row.rdList" :border="true">
              <el-table-column label="充值单号" prop="rechargeNo" />
              <el-table-column label="支付类型" align="center" prop="payWay">
                <template #default="scopeRd">
                  <dict-tag :options="busi_store_recharge_pay_way" :value="scopeRd.row.payWay" />
                </template>
              </el-table-column>
              <el-table-column label="退款单号" align="center" prop="refundNo" />
              <el-table-column label="退款类型" align="center" prop="refundWay">
                <template #default="scopeRd">
                  <dict-tag :options="busi_store_refund_details_type" :value="scopeRd.row.refundWay" />
                </template>
              </el-table-column>
              <el-table-column label="申请/实际退还次数" align="center" prop="applyRefundBalance">
                <template #default="scopeRd">
                  {{ parseInt(scopeRd.row.applyRefundBalance) }} / {{ parseInt(scopeRd.row.actualRefundBalance) }}
                </template>
              </el-table-column>
              <el-table-column label="申请/实际退款金额" align="center" prop="applyRefundAmount">
                <template #default="scopeRd"> {{ scopeRd.row.applyRefundAmount }} / {{ scopeRd.row.actualRefundAmount }} </template>
              </el-table-column>
              <el-table-column label="状态" align="center" prop="status">
                <template #default="scopeRd">
                  <dict-tag :options="busi_store_refund_details_status" :value="scopeRd.row.status" />
                </template>
              </el-table-column>
              <el-table-column label="退款结果" align="center" prop="refundResult" />
              <!-- <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template #default="scope">
                  {{ '操作' }}
                </template>
              </el-table-column> -->
            </el-table>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="医代名称" align="center" prop="agentMrName" />
        <el-table-column label="医代联系电话" align="center" prop="agentMrPhonenumber" />
        <el-table-column label="申请/实际退还次数" align="center" prop="applyRefundBalance">
          <template #default="scope"> {{ parseInt(scope.row.applyRefundBalance) }} / {{ parseInt(scope.row.actualRefundBalance) }} </template>
        </el-table-column>
        <el-table-column label="申请/实际退款金额" align="center" prop="applyRefundAmount">
          <template #default="scope"> {{ scope.row.applyRefundAmount }} / {{ scope.row.actualRefundAmount }} </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="status">
          <template #default="scope">
            <dict-tag :options="busi_store_refund_apply_status" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column label="审核员" align="center" prop="auditBy" />
        <el-table-column label="审核时间" align="center" prop="auditTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.auditTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="审核结果" align="center" prop="auditResult" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip v-if="scope.row.status === 0" content="同意审批" placement="top">
              <el-button
                v-hasPermi="['business:agentMrRefundApply:pass']"
                link
                type="success"
                icon="Check"
                @click="handlePassMr(scope.row)"
              ></el-button>
            </el-tooltip>
            <el-tooltip v-if="scope.row.status === 0" content="拒绝审批" placement="top">
              <el-button
                v-hasPermi="['business:agentMrRefundApply:reject']"
                link
                type="danger"
                icon="Close"
                @click="handleRejectMr(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" @pagination="getList" />
    </el-card>
    <!-- 添加或修改医代退款申请对话框 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="500px" append-to-body>
      <el-form ref="agentMrRefundApplyFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="国代ID" prop="agentGdId">
          <el-input v-model="form.agentGdId" placeholder="请输入国代ID" />
        </el-form-item>
        <el-form-item label="省代ID" prop="agentSdId">
          <el-input v-model="form.agentSdId" placeholder="请输入省代ID" />
        </el-form-item>
        <el-form-item label="系统用户ID" prop="sysUserId">
          <el-input v-model="form.sysUserId" placeholder="请输入系统用户ID" />
        </el-form-item>
        <el-form-item label="医代ID" prop="agentMrId">
          <el-input v-model="form.agentMrId" placeholder="请输入医代ID" />
        </el-form-item>
        <el-form-item label="医代名称" prop="agentMrName">
          <el-input v-model="form.agentMrName" placeholder="请输入医代名称" />
        </el-form-item>
        <el-form-item label="医代联系电话" prop="agentMrPhonenumber">
          <el-input v-model="form.agentMrPhonenumber" placeholder="请输入医代联系电话" />
        </el-form-item>
        <el-form-item label="申请退款次数" prop="applyRefundBalance">
          <el-input v-model="form.applyRefundBalance" placeholder="请输入申请退款次数" />
        </el-form-item>
        <el-form-item label="申请退款金额" prop="applyRefundAmount">
          <el-input v-model="form.applyRefundAmount" placeholder="请输入申请退款金额" />
        </el-form-item>
        <el-form-item label="实际退款次数" prop="actualRefundBalance">
          <el-input v-model="form.actualRefundBalance" placeholder="请输入实际退款次数" />
        </el-form-item>
        <el-form-item label="实际退款金额" prop="actualRefundAmount">
          <el-input v-model="form.actualRefundAmount" placeholder="请输入实际退款金额" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio v-for="dict in busi_store_refund_apply_status" :key="dict.value" :value="parseInt(dict.value)">{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="审核员" prop="auditBy">
          <el-input v-model="form.auditBy" placeholder="请输入审核员" />
        </el-form-item>
        <el-form-item label="审核时间" prop="auditTime">
          <el-date-picker v-model="form.auditTime" clearable type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择审核时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="审核结果" prop="auditResult">
          <el-input v-model="form.auditResult" placeholder="请输入审核结果" />
        </el-form-item>
        <el-form-item label="JSON串存储扩展字段" prop="otherVal">
          <el-input v-model="form.otherVal" placeholder="请输入JSON串存储扩展字段" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <!-- <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button> -->
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="AgentMrRefundApply" lang="ts">
import { listAgentMrRefundApply } from '@/api/business/agentMrRefundApply';
import { passMr, rejectMr } from '@/api/business/refund';
import { to } from 'await-to-js';
import { AgentMrRefundApplyVO, AgentMrRefundApplyQuery, AgentMrRefundApplyForm } from '@/api/business/agentMrRefundApply/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { busi_store_refund_apply_status } = toRefs<any>(proxy?.useDict('busi_store_refund_apply_status'));
const { busi_store_refund_details_status, busi_store_refund_details_type, busi_store_recharge_pay_way } = toRefs<any>(
  proxy?.useDict('busi_store_refund_details_status', 'busi_store_refund_details_type', 'busi_store_recharge_pay_way')
);

const agentMrRefundApplyList = ref<AgentMrRefundApplyVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const agentMrRefundApplyFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: AgentMrRefundApplyForm = {
  id: undefined,
  agentGdId: undefined,
  agentSdId: undefined,
  sysUserId: undefined,
  agentMrId: undefined,
  agentMrName: undefined,
  agentMrPhonenumber: undefined,
  applyRefundBalance: undefined,
  applyRefundAmount: undefined,
  actualRefundBalance: undefined,
  actualRefundAmount: undefined,
  status: undefined,
  auditBy: undefined,
  auditTime: undefined,
  auditResult: undefined,
  otherVal: undefined,
  remark: undefined
};
const data = reactive<PageData<AgentMrRefundApplyForm, AgentMrRefundApplyQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    agentGdId: undefined,
    agentSdId: undefined,
    sysUserId: undefined,
    agentMrId: undefined,
    agentMrName: undefined,
    agentMrPhonenumber: undefined,
    applyRefundBalance: undefined,
    applyRefundAmount: undefined,
    actualRefundBalance: undefined,
    actualRefundAmount: undefined,
    status: undefined,
    auditBy: undefined,
    auditTime: undefined,
    auditResult: undefined,
    otherVal: undefined,
    createTime: undefined,
    params: {}
  },
  rules: {
    id: [{ required: true, message: 'ID不能为空', trigger: 'blur' }],
    agentGdId: [{ required: true, message: '国代ID不能为空', trigger: 'blur' }],
    agentSdId: [{ required: true, message: '省代ID不能为空', trigger: 'blur' }],
    sysUserId: [{ required: true, message: '系统用户ID不能为空', trigger: 'blur' }],
    agentMrId: [{ required: true, message: '医代ID不能为空', trigger: 'blur' }],
    agentMrName: [{ required: true, message: '医代名称不能为空', trigger: 'blur' }],
    agentMrPhonenumber: [{ required: true, message: '医代联系电话不能为空', trigger: 'blur' }],
    applyRefundBalance: [{ required: true, message: '申请退款次数不能为空', trigger: 'blur' }],
    applyRefundAmount: [{ required: true, message: '申请退款金额不能为空', trigger: 'blur' }],
    actualRefundBalance: [{ required: true, message: '实际退款次数不能为空', trigger: 'blur' }],
    actualRefundAmount: [{ required: true, message: '实际退款金额不能为空', trigger: 'blur' }],
    status: [{ required: true, message: '状态不能为空', trigger: 'change' }],
    auditBy: [{ required: true, message: '审核员不能为空', trigger: 'blur' }],
    auditTime: [{ required: true, message: '审核时间不能为空', trigger: 'blur' }],
    auditResult: [{ required: true, message: '审核结果不能为空', trigger: 'blur' }],
    otherVal: [{ required: true, message: 'JSON串存储扩展字段不能为空', trigger: 'blur' }],
    remark: [{ required: true, message: '备注不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询医代退款申请列表 */
const getList = async () => {
  loading.value = true;
  const res = await listAgentMrRefundApply(queryParams.value);
  agentMrRefundApplyList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  agentMrRefundApplyFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: AgentMrRefundApplyVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
// const handleAdd = () => {
//   reset();
//   dialog.visible = true;
//   dialog.title = '添加医代退款申请';
// };

/** 修改按钮操作 */
// const handleUpdate = async (row?: AgentMrRefundApplyVO) => {
//   reset();
//   const _id = row?.id || ids.value[0];
//   const res = await getAgentMrRefundApply(_id);
//   Object.assign(form.value, res.data);
//   dialog.visible = true;
//   dialog.title = '修改医代退款申请';
// };

/** 提交按钮 */
// const submitForm = () => {
//   agentMrRefundApplyFormRef.value?.validate(async (valid: boolean) => {
//     if (valid) {
//       buttonLoading.value = true;
//       if (form.value.id) {
//         await updateAgentMrRefundApply(form.value).finally(() => (buttonLoading.value = false));
//       } else {
//         await addAgentMrRefundApply(form.value).finally(() => (buttonLoading.value = false));
//       }
//       proxy?.$modal.msgSuccess('操作成功');
//       dialog.visible = false;
//       await getList();
//     }
//   });
// };

/** 删除按钮操作 */
// const handleDelete = async (row?: AgentMrRefundApplyVO) => {
//   const _ids = row?.id || ids.value;
//   await proxy?.$modal.confirm('是否确认删除医代退款申请编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
//   await delAgentMrRefundApply(_ids);
//   proxy?.$modal.msgSuccess('删除成功');
//   await getList();
// };

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'business/agentMrRefundApply/export',
    {
      ...queryParams.value
    },
    `agentMrRefundApply_${new Date().getTime()}.xlsx`
  );
};

const handleRejectMr = async (row: AgentMrRefundApplyVO) => {
  const [err, res] = await to(
    ElMessageBox.prompt('请输入拒绝原因，拒绝后医代会解除冻结状态，可继续使用服务', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      closeOnClickModal: false,
      inputValidator: (value) => {
        if (!value) {
          return '拒绝原因必填';
        }
        return true;
      }
    })
  );
  if (!err) {
    await rejectMr(row.id, res.value);
    proxy?.$modal.msgSuccess('退款申请拒绝完成');
    await getList();
  }
};

const handlePassMr = async (row: AgentMrRefundApplyVO) => {
  const [err, res] = await to(
    ElMessageBox.prompt('请输入同意备注，同意后医代会解除冻结状态，并完成退款', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      closeOnClickModal: false,
      inputValidator: (value) => {
        if (!value) {
          return '同意备注必填';
        }
        return true;
      }
    })
  );
  if (!err) {
    await passMr(row.id, res.value);
    proxy?.$modal.msgSuccess('退款申请同意完成');
    await getList();
  }
};

onMounted(() => {
  getList();
});
</script>
